/**
 * @name TimeList
 * @desc 日期列表
 * @author 方知有
 * @date 2020/09/03
 */
import React, { Component } from "react";
import { leaperWeek, leaperMonth, leaperDate, leaperTerm } from "@/utils/now-date";
import { DatePicker, message, Modal, Input } from "antd";
import moment from "moment";
import { getSearchObject } from "@/utils";
import styles from "./styles.module.less";
const { RangePicker, WeekPicker, MonthPicker } = DatePicker;
const timeList = [
  { code: 0, name: "全部" },
  { code: 1, name: "本日" },
  { code: 2, name: "本周" },
  { code: 3, name: "本月" },
  { code: 4, name: "本学期" }
];
const dateFormat = "YYYY-MM-DD";
const timeListTwo = [
  { code: 1, name: "日" },
  { code: 2, name: "周" },
  { code: 3, name: "月" },
  { code: 4, name: "年" }
];
const defaultDate = moment(new Date()).format(dateFormat);
class Timeist extends Component {
  state = {
    timeCode: 0,
    startTime: null,
    endTime: null
  };
  /**
   * @name typeChange
   * @param code number 类型code
   */
  typeChange = (code) => {
    this.setState({ timeCode: code }, () => {
      this.times();
    });
  };

  /**
   * @name times
   * @description 时间类型所对应的时间
   * @param string YYYY-MM-DD
   */
  times = () => {
    const { timeCode } = this.state;
    let startTime = "";
    let endTime = "";
    if (timeCode === 1) {
      const time = leaperDate();
      startTime = time.today;
      endTime = time.today;
    } else if (timeCode === 2) {
      const time = leaperWeek();
      startTime = time.mondy;
      endTime = time.sundy;
    } else if (timeCode === 3) {
      const time = leaperMonth();
      startTime = time.start_month;
      endTime = time.end_month;
    } else if (timeCode === 4) {
      const time = leaperTerm();
      startTime = time.termstart;
      endTime = time.termend;
    } else {
      startTime = null;
      endTime = null;
    }
    this.setState({ startTime, endTime });
  };
  /**
   * @name getRangePikcer
   * @desc 日期选择
   * @param value 标准时间[moment,moment]
   * @param dateString 字符串[YYYY-MM-DD,YYYY-MM-DD]
   */
  getRangePikcer = (value, dateString) => {
    console.log("value===", value, dateString);
    this.setState({ startTime: dateString[0], endTime: dateString[1] }, () => {
      this.pickerTimeChange();
    });
  };

  /**
   * @name pickerTimeChange
   * @description 自选日期对按钮日期影响
   */
  pickerTimeChange = () => {
    const timeDay = leaperDate();
    const timeWeek = leaperWeek();
    const timeMonth = leaperMonth();
    const timeTerm = leaperTerm();
    const today = timeDay.today;
    const weekStart = timeWeek.mondy;
    const weekEnd = timeWeek.sundy;
    const monthStart = timeMonth.start_month;
    const monthEnd = timeMonth.end_month;
    const termStart = timeTerm.termstart;
    const termEnd = timeTerm.termend;
    const { startTime, endTime } = this.state;
    let code = "";
    if (!startTime && !endTime) {
      code = 0;
    } else if (startTime === today && endTime === today) {
      //今天
      code = 1;
    } else if (startTime === weekStart && endTime === weekEnd) {
      //本周
      code = 2;
    } else if (startTime === monthStart && endTime === monthEnd) {
      //本月
      code = 3;
    } else if (startTime === termStart && endTime === termEnd) {
      //本学期
      code = 4;
    }
    this.setState({ timeCode: code });
  };
  render() {
    const { yui = "", mio = "", ritsu = "", mugi = "", azusa = "", test = "" } = getSearchObject();
    const { timeCode, startTime, endTime } = this.state;
    return (
      <div>
        <div className={styles.content}>
          <div className={styles.ul}>
            {timeList.map((v) => (
              <li key={v.code} className={`${styles.inline} ${timeCode === v.code ? styles.active : null}`} onClick={() => this.typeChange(v.code)}>
                {v.name}
              </li>
            ))}
          </div>
          <RangePicker
            style={{ minWidth: "210px", maxWidth: "15%", marginLeft: "2%" }}
            value={!startTime ? null : [moment(startTime, dateFormat), moment(endTime, dateFormat)]}
            onChange={this.getRangePikcer}
          />
        </div>
        <p>getSearchObject</p>
        <p>{yui}</p>
        <p>{mio}</p>
        <p>{ritsu}</p>
        <p>{mugi}</p>
        <p>{azusa}</p>
        <p>{test}</p>
        <Anothertime />
      </div>
    );
  }
}
export default Timeist;

class Anothertime extends Component {
  state = {
    timeCode: 1, //时间code
    startTime: defaultDate, //开始时间
    endTime: defaultDate, //结束时间
    time: defaultDate, //日期
    yearSelect: false //年份选择面板
  };
  /**
   * @name typeChange
   * @param {Number} code 类型code
   * @description 时间类型变化
   */
  typeChange = (code) => {
    this.setState({ timeCode: code });
    this.times(code);
  };
  /**
   * @name times
   * @param string YYYY-MM-DD
   * @description 时间类型所对应的时间
   */
  times = (timeCode) => {
    this.timeCommon(timeCode, new Date());
  };
  /**
   * @name newTimeChange
   * @param {Object} date 标准时间
   * @param {String} dateString 当前选中时间字符串
   * @description 时间变化
   */
  newTimeChange = (date) => {
    const { timeCode } = this.state;
    this.timeCommon(timeCode, date);
  };
  /**
   * @name timeCommon
   * @param {Number} timeCode 时间类型
   * @param {Object} time 标准时间
   * @description 时间变化公用方法
   */
  timeCommon = (timeCode, date) => {
    let startTime = "";
    let endTime = "";
    let time = moment(date).format(dateFormat);
    if (timeCode === 1) {
      startTime = time;
      endTime = time;
    } else if (timeCode === 2) {
      startTime = moment(time).startOf("week").format(dateFormat);
      endTime = moment(time).endOf("week").format(dateFormat);
    } else if (timeCode === 3) {
      startTime = moment(time).startOf("month").format(dateFormat);
      endTime = moment(time).endOf("month").format(dateFormat);
    } else if (timeCode === 4) {
      let year = moment(time).format("YYYY");
      startTime = year + "-01-01";
      endTime = year + "-12-31";
      time = startTime;
    }
    this.setState({ startTime, endTime, time, yearSelect: false });
  };
  /**
   * @name openYearSelect
   * @description 年分选择面板展示与否
   */
  openYearSelect = () => {
    this.setState({ yearSelect: true });
  };
  render() {
    const { timeCode, time, yearSelect, startTime, endTime } = this.state;
    return (
      <div>
        <TimeChange
          time={time}
          timeCode={timeCode}
          yearSelect={yearSelect}
          typeChange={this.typeChange}
          newTimeChange={this.newTimeChange}
          openYearSelect={this.openYearSelect}
        />
        <TimeRange />
      </div>
    );
  }
}
class TimeChange extends Component {
  render() {
    // newTermChange = () => {}
    const { time, timeCode, yearSelect, typeChange = () => {}, newTimeChange = () => {}, openYearSelect = () => {} } = this.props;
    return (
      <div className={styles.time_content}>
        时间段：
        <div className={styles.ul}>
          {timeListTwo.map((v) => (
            <li key={v.code} className={`${styles.inline} ${timeCode === v.code ? styles.active : null}`} onClick={() => typeChange(v.code)}>
              {v.name}
            </li>
          ))}
        </div>
        {timeCode === 1 ? (
          <DatePicker allowClear={false} value={moment(time, dateFormat)} onChange={newTimeChange} />
        ) : timeCode === 2 ? (
          <WeekPicker allowClear={false} value={moment(time, dateFormat)} onChange={newTimeChange} />
        ) : timeCode === 3 ? (
          <MonthPicker allowClear={false} value={moment(time, dateFormat)} onChange={newTimeChange} />
        ) : (
          <DatePicker
            value={moment(time, dateFormat)}
            open={yearSelect}
            mode="year"
            format="YYYY"
            onOpenChange={openYearSelect}
            onPanelChange={newTimeChange}
            allowClear={false}
          />
        )}
      </div>
    );
  }
}

class TimeRange extends Component {
  state = {
    resKeyStime: "",
    resKeyEtime: "",
    inpValue: ""
  };
  times = null;
  input = null;
  componentDidMount() {
    // if (this.input) {
    //   console.log("input-===", this.input);
    //   this.input.focus();
    // }
  }
  componentWillUnmount() {
    if (this.times) {
      clearInterval(this.times);
    }
  }
  /**
   * @anme timeDisable
   * @param {String} type
   * @param {Object} time
   * @description 时间范围判断
   */
  timeDisable = (type, time) => {
    const { resKeyStime, resKeyEtime } = this.state;
    if (!resKeyStime && !resKeyEtime) {
      return;
    }
    console.log("time.valueOf()===", time.valueOf(), resKeyEtime.valueOf());
    if (type === "resKeyStime") {
      //开始时间 > 结束时间
      return time.valueOf() > resKeyEtime.valueOf();
    } else {
      return time.valueOf() < resKeyStime.valueOf();
    }
  };
  /**
   * @name timeChange
   * @param {String} key
   * @param {Object} val
   * @description 时间变化-开始-截止-时间戳
   */
  timeChange = (key, val) => {
    this.setState({ [key]: val });
  };
  /**
   * @name confirms
   * @description 时间范围modale
   */
  confirms = () => {
    const { resKeyStime, resKeyEtime } = this.state;
    Modal.confirm({
      title: "",
      content: (
        <React.Fragment>
          <DatePicker
            allowClear={false}
            format={dateFormat}
            defaultValue={resKeyStime ? resKeyStime : null}
            disabledDate={(e) => this.timeDisable("resKeyStime", e)}
            // disabledDate={this.timeStartDisable}
            placeholder={"请选择开始时间"}
            style={{ width: "180px" }}
            onChange={(e) => this.timeChange("resKeyStime", e)}
          />
          <DatePicker
            allowClear={false}
            format={dateFormat}
            defaultValue={resKeyEtime ? resKeyEtime : null}
            disabledDate={(e) => this.timeDisable("resKeyEtime", e)}
            // disabledDate={this.timeEndDisable}
            placeholder={"请选择结束时间"}
            onChange={(e) => this.timeChange("resKeyEtime", e)}
          />
        </React.Fragment>
      )
      // onOk:()=>{},
    });
  };
  /**
   * @name inpFocus
   * @returns 手动控制modal-自动聚焦
   */
  inpFocus = () => {
    this.times = setInterval(() => {
      console.log("000000000", this.input);
      if (this.input && this.times) {
        this.input.focus();
        clearInterval(this.times);
      }
    }, 100);
  };
  /**
   * @name onCancel
   * @param {Object} modals modal元素
   * @description 销毁modal
   */
  onCancel = (modals) => {
    modals.destroy();
  };
  /**
   * @name modalContral
   * @param {Object} modals modal元素
   * @description 有条件的选择是否销毁modal
   */
  modalContral = (modals) => {
    const { inpValue } = this.state;
    //剔除字符串中所有空格
    let value = inpValue ? inpValue.replace(/\s/g, "") : "";
    if (value) {
      this.onCancel(modals);
    } else {
      message.warning("请输入有效内容");
    }
  };
  //手动控制confirm
  confirmTwo = () => {
    let modals = Modal.confirm({
      title: "手动控制confirm",
      content: (
        <div>
          <Input.TextArea
            ref={(refs) => (this.input = refs)}
            defaultValue={this.state.inpValue}
            onChange={(e) => this.setState({ inpValue: e.target.value })}
          />
          {this.inpFocus()}
        </div>
      ),
      //e-非常重要,阻止了自动关闭
      onOk: (e) => {
        this.modalContral(modals);
      }
    });
  };
  render() {
    return (
      <React.Fragment>
        {/**<Input value={this.state.inpValue} ref={(refs) => (this.input = refs)} onChange={(e) => this.setState({ inpValue: e.target.value })} /> */}
        <div onClick={this.confirms}>hahahaha</div>
        <div onClick={this.confirmTwo}>ererere</div>
      </React.Fragment>
    );
  }
}
